define(function(require, exports, module) {
	"use strict";
	require("../../dep/mui/js/mui.min.js");
	require("../jquery-3.1.1.min.js");
	require("../mui.picker.min.js");
	require("../dateShow.js");
	require("./dateInput.js");
	var globalInit = require("globalInit"); //共用js
	var muiTips = require("muiTips");
	require("keepDate");
	var template = require("template");

	var abpUse = require("../abp.js");
	var abp = abpUse.abpstart;
	require('http://g.alicdn.com/ilw/ding/0.8.9/scripts/dingtalk.js');
	//返回清除缓存
	var dingTalkNav = require('dd_config');
	var examinaSourceId = 0; //启用审批需传参数

	mui.init({
		swipeBack: true //启用右滑关闭功能
	});

	var getFunList = require("../getFunList/getFunList.js"); //函数配置js
	//钉钉右边按钮操作
	dingTalkNav.RightNavBar(false, "新增", "default");
	getFunList.addGoodsInfoList("goodsList", "#goodsListShow"); //新增订单选择货品列表展示

	//编辑订单
	var updateSell = require("./updateSell.js");

	//	if($("#companyName").attr("data-id")&& $("#valorem").attr("data-id")&&$("#staff-user").attr("data-id")){
	//      	$("#sub-btn").show();
	//      }else{
	//      	$("#sub-btn").hide();
	//      }

	$(function() {

		var sellData = JSON.parse(sessionStorage.getItem("sellData"));
		//计算数量与金额 删除明细
		//		var deleteProductDetail = require("./deleteProductDetail.js");
		if(sessionStorage.goodsInfoList) {
			//计算总数量与金额
			updateSell.allnumAndAllMoney();
			//删除订单明细
			var goodsLists = JSON.parse(sessionStorage.goodsInfoList);
			updateSell.deleteGoodsDetail({
				"delete": ".delete-trash", //删除按钮
				"array": goodsLists, //需要删除的数组
				"goodsIn": ".goodsIn", //移除页面元素
				"goodsInfoList": "goodsInfoList", //需要存储的数组对象
			}, hideList);
		}
		if(sellData) {
			//删除编辑状态下的订单明细
			updateSell.deleteUpdateGoodsDetail({
				"update": ".update-trash", //删除按钮
				"goodsInList": ".goodsIn-list", //移除页面元素
				"data": sellData,
				"updateArr": sellData.buyDetail,
				"sellData": "sellData" //需要存储的数组对象
			}, hideList);
		}
		if(!sellData) {
			updateSell.buySerialNo();
		} else {
			examinaSourceId = Number(sellData.id); //修改启用审批需传参数
			$("#sub-btn").show();
			updateSell.updateModel({
				"sellData": sellData, //后台数据
				"code": "#code", //编号标签ID
				"createDate": ".createDate", //创建时间
				"lastDate": ".lastDate", //预交时间
				"companyName": "#companyName", //供应商标签ID
				"busUserName": "#staff-user", //负责人标签ID
				"valorem": "#valorem", //计税方式标签ID
				"goodsInfo": "goodsInfo", //货品template模板ID
				"goodsListShow": "#goodsListShow", //mainID
				"lastInfo": "#lastInfo", //总金额父盒子
				"allNumber": "#goodsListShow .goodsNum", //总数量
				"allMoney": "#goodsListShow .product-money", //总金额
				"allNum": "#allNum", //总数量赋值
				"allPrice": "#allPrice", //总金额
				"notes": "#notes"
			});
			//点击客户
			mui("body").on("tap", "#companyName", function() {
				session();
			});
			//负责人	
			mui("body").on("tap", "#staff-user", function() {
				session();
			});
			//计税方式
			mui("body").on("tap", "#valorem", function() {
				session();
			});
			//点击选择货品
			mui("body").on("tap", "#chioce-product", function() {
				session();
			});
			//点击货品明细存储值
			mui("body").on("tap", "#goodsListShow li", function() {
				session();
			});

		}

		function session() {
			sellData.serialNo = $("#code").text();
			sellData.dataCreated = $(".createDate").text();
			sellData.deliveryDate = $(".lastDate").text();
			sellData.companyName = $("#companyName").text();
			sellData.companyId = $("#companyName").attr("data-id");
			sellData.busUserName = $("#staff-user").text();
			sellData.busUserId = $("#staff-user").attr("data-id");
			sellData.taxRateType = $("#valorem").attr("data-id");
			sellData.taxRateTypeName = $("#valorem").text();
			sessionStorage.setItem("sellData", JSON.stringify(sellData));
		}

		//选择供应商及税率 以及负责人
		var chioceInfo = require("./chioceInfo.js");
		chioceInfo.chioceMore();
		//计算金额
		updateSell.allnumAndAllMoney();
		
		function dataModels(statusId) {
			var PirchaseID = sessionStorage.getItem("PirchaseID");
			var serialNo = $("#code").text().trim();
			var dataCreated = $(".createDate").text().trim(); //创建日期
			var deliveryDate = $(".lastDate").text().trim(); //预交日期
			var companyName = $("#companyName").text().trim();
			var companyId = Number($("#companyName").attr("data-id")); //客户ID
			var busUserId = Number($("#staff-user").attr("data-id")); //暂时设置为1
			var taxRateType = Number($("#valorem").attr("data-id"));
			var notes = $(".remarks").val().trim();
			var dataModel = {
				"preAmount": 0, //(number, optional): 预付金额 
				"accountId": 0, //(integer, optional): 预付账号 
				"sourceType": 0, //(integer, optional): 来源类型 
				"sourceSerial": "", //(string, optional): 来源单号 
				"sourceId": 0, //来源id
				//					"buyDetail": [BuyDetailInput],    //采购单明细 ,
				"deliveryDate": deliveryDate, //预交日期
				"taxRateType": taxRateType, //计税类型 
				"currencySerial": "RMB", //币别
				"currencyName": "人民币", //币别名称 
				"currencyRate": 1, //汇率
				"serialNo": serialNo, //订单编号
				"serialDate": dataCreated, //创建日期
				"companyId": companyId, //(integer): 客户 
				"contactId": 0, //(integer): 联系人 ,
				"busUserId": busUserId, //业务员ID
				"deptId": 0, //(integer): 部门 ,
				"statusId": statusId, //(integer): 提交状态 ,
				"notes": notes, //(string): 备注 ,
				"id": PirchaseID //(integer, optional): Id
			};
			//
			dataModel.buyDetail = [];
			//					
			var productionList = $(".production-list");
			for(var i = 0; i < productionList.length; i++) {
				var whId = Number($(".production-list").eq(i).find(".warehouse").data("id"));
				var goodsId = Number($(".production-list").eq(i).find(".clothes-code").data("id"));
				var goodsUnit = $(".production-list").eq(i).find(".clothes-code").data("unit");
				var price = Number($(".production-list").eq(i).find(".price").text());
				var goodsNum = Number($(".production-list").eq(i).find(".goodsNum").text());
				var taxes = Number($(".production-list").eq(i).data("taxes"));
				var discount = Number($(".production-list").eq(i).data("discount"));
				var notes = $(".production-list").eq(i).data("notes");
				var BuyDetailInput = {
					"whId": whId, // (integer, optional): 仓库 ,
					"goodsId": goodsId, // (integer, optional): 货品id ,
					"unit": goodsUnit, // (string): 单位 ,
					"price": price.toFixed(6), // (number): 单价 ,
					"discount": discount.toFixed(2), // (number): 折扣 ,
					"taxRate": taxes.toFixed(2), // (number): 税率 ,
					"unitCode": goodsUnit, // (string): 副单位 ,
					"unitCodeNumber": goodsNum.toFixed(6), // (number): 副单位数量 ,
					"notes": notes, // (string): 备注 ,
					"unitCodeConvertRate": 1, // (number): 副单位转换率 ,
					"unitCode1": "", // (string): 副单位1 ,
					"unitCodeConvertRate1": 0, // (number): 副单位1转换率 ,
					"unitCode2": "", // (string): 副单位2 ,
					"unitCodeConvertRate2": 0, // (number): 副单位2转换率 ,
					"unitCodeAssist": "", // (string): 辅单位 ,
					"unitCodeNumberAssist": 0, // (number): 辅单位数量 ,
					"isGift": false, // (boolean): 是否赠品 ,
					"storageId": 0, // (integer, optional): 储位 ,
					"sourceType": 0, // (integer): 来源类型 ,
					"sourceSerial": "", // (string, optional): 来源单号 ,
					"sourceId": 0, // (integer): 来源id ,
					"sourceItemId": 0, // (integer): 来源明细id ,
					"id": 0, // (integer, optional): Id
				};
				dataModel.buyDetail.push(BuyDetailInput);
			}
			return dataModel;
		}

		function buyOrder(dataModel) { //请求函数
			var option = {};
			//	console.log(dataModel.buyDetail);
			abp.services.app.buyList.create(dataModel, option)
				.done(function(data) {
					//	            	mui.alert('<ul class="mui-row pop-tabmain"><li class="mui-col-xs-6 mui-col-sm-6"style="text-align: right;padding-right: 20px;"><a class="yuanico"><span>√</span></a></li><li class="mui-col-xs-6 mui-col-sm-6" style="text-align: left;line-height: 46px;">保存成功</li></ul>', ' ', function() {
					//				    	clearSession();
					//						document.location.href = "../purchase/index.html";
					//										
					//	            	},'div');  
					function locaHref() {
						document.location.href = "../../src/purchase/index.html?dd_nav_bgcolor=FFFF943E";
					}
					if(dataModel.statusId == abp.statusId.Draft) {
						muiTips.alertTips(' ', "保存成功", 1, 3, locaHref);
					} else {
						muiTips.alertTips(' ', "提交成功", 1, 3, locaHref);
					}
					clearSession();
					if(data.success) {
						console.log(data);
					} else {}
				})
				.fail(function(data) {
					muiTips.alertTips(' ', data.message, 2, 3, "default");
					globalInit.buttonReset(".btnDisabledText");
				});
		}

		function buyOrderUpdate(dataModel) { //请求函数
			//alert(dataModel.statusId)
			var option = {};

			function locaUpdateHref() {
				document.location.href = "../../src/purchase/purchaseDetail.html?dd_nav_bgcolor=FFFF943E";
			}
			abp.services.app.buyList.update(dataModel, option)
				.done(function(data) {
					if(dataModel.statusId == abp.statusId.Draft) {

						muiTips.alertTips(' ', "修改成功", 1, 3, locaUpdateHref);
					} else {

						muiTips.alertTips(' ', "提交成功", 1, 3, locaUpdateHref);
					}
					clearSession();
					if(data.success) {
						//						console.log(data);
					} else {}
				})
				.fail(function(data) {

					muiTips.alertTips(' ', data.message, 2, 3, "default");
					globalInit.buttonReset(".btnDisabledText");
				});
		}
		//隐藏按钮与总金额
		hideList();

		function hideList() {
			var companyDataId = $("#companyName").attr("data-id");
			var valoremId = $("#valorem").attr("data-id");
			var staffId = $("#staff-user").attr("data-id");
			if($("#goodsListShow .product-money").length > 0) {
				$("#lastInfo").show();
				$("#goodsListShow").show();
			} else {
				$("#lastInfo").hide();
				$("#goodsListShow").hide();
			}
			if(($("#goodsListShow .product-money").length > 0) && companyDataId && valoremId && staffId) {

				$("#sub-btn").show();
			} else {
				$("#sub-btn").hide();
			}

		}

		//未入库
		mui("body").on("tap", ".mui-btn-sub", function() {
			globalInit.buttonInit(".mui-btn-sub");
			var dataModel = dataModels(abp.statusId.Pending);
			if(!dataModel.id || dataModel.id === undefined) {
				buyOrder(dataModel);
			} else {
				buyOrderUpdate(dataModel);
			}
		});
		//草稿
		mui("body").on("tap", ".keep-draft", function() {
			globalInit.buttonInit(".keep-draft");
			var dataModel = dataModels(abp.statusId.Draft);
			if(!dataModel.id || dataModel.id === undefined) {
				buyOrder(dataModel);
			} else {
				buyOrderUpdate(dataModel);
			}
		});
		//设置计税参数配置
		mui("body").on("tap", ".setParm", function() {
			sessionStorage.setParm = $("#valorem").attr("data-id");
			sessionStorage.removeItem("localstatusType");
			sessionStorage.removeItem("statusType");
		});

		mui("body").on("tap", "#goodsListShow .goodsIn", function() {
			sessionStorage.setParm = $("#valorem").attr("data-id");
			sessionStorage.setItem("goodsIndex", $(this).attr("data-id"));
			sessionStorage.setItem("localstatusType", $(this).attr("data-other"));
			sessionStorage.removeItem("goodsId");
			sessionStorage.removeItem("statusType");
			sessionStorage.removeItem("chioce");
		});
		mui("body").on("tap", "#goodsListShow .goodsIn-list", function() {
			sessionStorage.setParm = $("#valorem").attr("data-id");
			sessionStorage.setItem("goodsIndex", $(this).attr("data-id"));
			sessionStorage.setItem("statusType", $(this).attr("data-status"));
			sessionStorage.removeItem("goodsId");
			sessionStorage.removeItem("localstatusType");
			sessionStorage.removeItem("chioce");
		});

		//点击返回清楚缓存
		mui("body").on("tap", "header>button", function() {

			//			sessionStorage.removeItem("PirchaseID");
			clearSession();

		});

		if(sessionStorage.getItem("sellData")) {
			//ios
			dingTalkNav.LeftNavBar(clearSessionDD);
			//ad
			dingTalkNav.leftAndroid(clearSessionDD);
			//update
			dingTalkNav.setTitleText("编辑采购订单");
		} else if(sessionStorage.getItem("createHome")) {
			//ios
			dingTalkNav.LeftNavBar(clearSessionDDHome);
			//ad
			dingTalkNav.leftAndroid(clearSessionDDHome);
			//新增采购订单
			dingTalkNav.setTitleText("新增采购订单");
		} else {
			//ios
			dingTalkNav.LeftNavBar(clearSessionDDList);
			//ad
			dingTalkNav.leftAndroid(clearSessionDDList);
			//新增采购订单
			dingTalkNav.setTitleText("新增采购订单");
		}

		function clearSession() {
			sessionStorage.removeItem("chioceClientName");
			sessionStorage.removeItem("chioceClientNameId");
			sessionStorage.removeItem("valoremName");
			sessionStorage.removeItem("valoremNameId");
			sessionStorage.removeItem("chioceStaff");
			sessionStorage.removeItem("chioceStaffId");
			sessionStorage.removeItem("chioceSupplierName");
			sessionStorage.removeItem("chioceSupplierNameId");
			sessionStorage.removeItem("clientId");
			sessionStorage.removeItem("goodsInfoList");
			sessionStorage.removeItem("statusType");
			sessionStorage.removeItem("localstatusType");
			sessionStorage.removeItem('serialNo');
			sessionStorage.removeItem('sellData');
			sessionStorage.removeItem('inPurchaseData');
			sessionStorage.removeItem("data-stockQuery");
			sessionStorage.removeItem("flags");
			sessionStorage.removeItem('goodsUnit');
			sessionStorage.removeItem('setParm');
			sessionStorage.removeItem('supplierId');
			sessionStorage.removeItem('createHome'); //新增标识
		}
		//编辑
		function clearSessionDD() {
			clearSession();
			document.location.href = "../../src/purchase/purchaseDetail.html?dd_nav_bgcolor=FFFF943E";
		}
		//
		function clearSessionDDList() {
			clearSession();
			document.location.href = "../../src/purchase/index.html?dd_nav_bgcolor=FFFF943E";
		}
		//
		function clearSessionDDHome() {
			clearSession();
			document.location.href = "../../src/index.html?dd_nav_bgcolor=FFFF943E";
		}

	});

	//判断是否启用审批
	var eHistory = require("eHistory");
	var isExamina = eHistory.funIsAuditSetting(abp.sourceType.BUY, examinaSourceId);
	if(isExamina === true) {
		$("#btnSubmitExamina").text("提交审核");
	} else {
		$("#btnSubmitExamina").text("提交");
	}

});